package controllers;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import constants.Default;
import constants.TplPath;
import constants.system.MemberShip;
import constants.ws.PageBean;
import duppentity.dto.sys.SysDtoUtil;
import duppentity.dto.sys.SysItemDto;
import duppentity.dto.sys.SysRoleDto;
import utils.JsonUtils;
import utils.Utils;

import java.util.*;

/**
 * @author yangz
 * @desc 角色管理
 */
public class RoleController extends ApiController {
    /**
     * 角色列表
     */
    public static void roleList(){
        String page = TplPath.roleList;
        if (Utils.exitFile(page)){
            renderTemplate(page);
        }
    }

    public static void getRoleList() {
        PageBean pageBean = PageBean.get();

        JsonObject data = roleDupp.getRoleList(pageBean.getOffset(), pageBean.pageCount());
        if (!checkResult(data)) {
            apiError(data);
        }
        List<SysRoleDto> sysRoleDtoList = SysDtoUtil.getSysRoleListDto(data);
        apiList(data, sysRoleDtoList);
    }

    public static void addRole(){
        String page = TplPath.addRole;
        String dataJson = ItemController.getDataJson();
        if (Utils.exitFile(page)){
            renderTemplate(page,dataJson);
        }
    }

    public static void editRole(){
        String page = TplPath.editRole;
        Long id = params.get("id",Long.class);
        JsonObject result = null;
        if (id>0) {
            result =roleDupp.getRole(id);
        }
        if (result!=null) {
            SysRoleDto roleDto = SysDtoUtil.getSysRoleDto(result);

            List<Long> roleItemIds = roleDto.roleItemIds;

            JsonObject data = itemDupp.getItemList(0,Integer.MAX_VALUE);
            if (!checkResult(data)) {
                apiError(data);
            }
            List<SysItemDto> sysItemDtoList = SysDtoUtil.getSysItemListDto(data);
            //排序
            Collections.sort(sysItemDtoList, new Comparator<SysItemDto>() {
                @Override
                public int compare(SysItemDto o1, SysItemDto o2) {
                    return o1.sequence.compareTo(o2.sequence);
                }
            });

            List<JsonObject> zeroList = new ArrayList<>();
            List<JsonObject> oneList = new ArrayList<>();
            List<JsonObject> twoList = new ArrayList<>();
            if (sysItemDtoList.size() > 0) {
                for (Integer i = 0; i < sysItemDtoList.size(); i++) {
                    SysItemDto itemDto = sysItemDtoList.get(i);
                    JsonObject tmp = new JsonObject();
                    if (itemDto.level.equals(Default.itemLevel.zero)) {
                        tmp.addProperty("id", itemDto.id);
                        tmp.addProperty("title", itemDto.name);
                        tmp.addProperty("checked",false);
                         if(roleItemIds.contains(Long.parseLong(itemDto.id))){
                             tmp.addProperty("checked",true);
                         }
                        zeroList.add(tmp);
                    } else if (itemDto.level.equals(Default.itemLevel.one)) {
                        tmp.addProperty("id", itemDto.id);
                        tmp.addProperty("parentId", itemDto.parentId);
                        tmp.addProperty("title", itemDto.name);
                        oneList.add(tmp);
                    } else if (itemDto.level.equals(Default.itemLevel.two)) {
                        tmp.addProperty("id", itemDto.id);
                        tmp.addProperty("parentId", itemDto.parentId);
                        tmp.addProperty("title", itemDto.name);
                        twoList.add(tmp);
                    }
                }
            }

            for (Integer a = 0; a < zeroList.size(); a++) {
                //顶级
                JsonObject aJson = zeroList.get(a).getAsJsonObject();
                List<JsonObject> oneContents = new ArrayList<>();
                for (Integer b = 0; b < oneList.size(); b++) {

                    JsonObject bJson = oneList.get(b).getAsJsonObject();
                    if (bJson.get("parentId").getAsLong() == aJson.get("id").getAsLong()) {
                        JsonObject content1 = new JsonObject();
                        content1.addProperty("id", bJson.get("id").getAsString());
                        content1.addProperty("title", bJson.get("title").getAsString());
                        if (roleItemIds.contains(bJson.get("id").getAsLong())) {
                            content1.addProperty("checked", true);
                        }else{
                            content1.addProperty("checked", false);
                        }
                        List<JsonObject> twoContents = new ArrayList<>();

                        for (Integer c = 0; c < twoList.size(); c++) {
                            JsonObject cJson = twoList.get(c).getAsJsonObject();
                            if (cJson.get("parentId").getAsLong() == bJson.get("id").getAsLong()) {
                                JsonObject content2 = new JsonObject();
                                content2.addProperty("id", cJson.get("id").getAsString());
                                content2.addProperty("title", cJson.get("title").getAsString());
                                content2.addProperty("level", Default.itemLevel.two);
                                twoContents.add(content2);
                                //isLevelTwo = true;
                                if(roleItemIds.contains(cJson.get("id").getAsLong())){
                                    content2.addProperty("checked", true);
                                }else{
                                    content2.addProperty("checked", false);
                                }
                            }
                        }

                        content1.add("children", JsonUtils.toJsonTree(twoContents));
                        content1.addProperty("spread", Boolean.TRUE);
                        content1.addProperty("level", Default.itemLevel.one);
                        oneContents.add(content1);
                    }
                    aJson.addProperty("spread", Boolean.TRUE);
                    aJson.addProperty("level", Default.itemLevel.zero);
                    aJson.add("children", JsonUtils.toJsonTree(oneContents));
                }
            }
            String dataJson = JsonUtils.formatJson(zeroList).replaceAll("\"(\\w+)\"(\\s*:\\s*)", "$1$2");

            if (Utils.exitFile(page)) {
                renderTemplate(page,roleDto,dataJson);
            }
        }
    }

    /**
     * 保存角色
     */
    public static void saveRole(){
        Long id = params.get("id",Long.class);

        String name = params.get("name",String.class);
        String itemIds = params.get("itemIds",String.class);
        if(Utils.isNullOrEmpty(itemIds)){
            apiError("请选择权限");
        }

        List<Long> ids = Utils.toLongList(itemIds);
        MemberShip memberShip = MemberShip.current();
        if (id!=null && id > 0) {
            JsonObject data = roleDupp.editRole(memberShip.getSessionId(),memberShip.getId(),id, name,ids,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("result").getAsBoolean()) {
                    apiOk("修改角色成功");
                } else {
                    apiError("修改角色失败");
                }
            } else {
                apiError(data);
            }
        } else {
            JsonObject data = roleDupp.addRole(memberShip.getSessionId(),memberShip.getId(),name,ids,MemberShip.current().getId());
            if (checkResult(data)) {
                if (data.get("id").getAsLong() > 0) {
                    apiOk("保存角色成功");
                } else {
                    apiError("保存角色失败");
                }
            } else {
                apiError(data);
            }
        }
    }


    public static void deleteRole() {
        Long id = params.get("id", Long.class);

        JsonObject data = roleDupp.deleteRole(id, MemberShip.current().getId());
        if (checkResult(data)) {
            if (data.get("result").getAsBoolean()) {
                apiOk("删除角色成功");
            } else {
                apiError("删除角色失败");
            }
        } else {
            apiError(data);
        }
    }

}
